package gui;

import dto.HorarioDTO;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.time.DayOfWeek;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import logic.Horario;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class UserHorariosDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private int idMedico;
  private ArrayList<HorarioDTO> horarios;

  public UserHorariosDialog(java.awt.Frame parent, boolean modal, int idMedico) {
    super(parent, modal);
    initComponents();
    setUpDayComboBox(diajComboBox);
    setUpHourComboBox(hourjComboBox);
    setUpMinuteComboBox(minutejComboBox);
    setUpHorasDeTrabajoComboBox(horasDeTrabajojComboBox);

    this.idMedico = idMedico;

    preBusqueda();

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

  public ArrayList<HorarioDTO> Horarios() {
    return horarios;
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  private void preBusqueda() {
    try {
      horarios = Horario.SearchByMedicoID(idMedico);
      updateHorarios(horarios);
    } catch (SQLException ex) {
      Logger.getLogger(UserHorariosDialog.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private void updateHorarios(ArrayList<HorarioDTO> dtos) {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("Día");
    m.addColumn("Desde las");
    m.addColumn("Hasta las");

    for (HorarioDTO dto : dtos) {
      m.addRow(
        new Object[]{
          InputHelper.DayConverter(dto.getDia()),
          dto.getHoraDesde(),
          dto.getHoraHasta()
        }
      );
    }
    horariosjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    horariosjTable.setModel(m);
  }

  private void setUpDayComboBox(JComboBox c) {
    DayOfWeek[] days = {
      DayOfWeek.MONDAY,
      DayOfWeek.TUESDAY,
      DayOfWeek.WEDNESDAY,
      DayOfWeek.THURSDAY,
      DayOfWeek.FRIDAY,
      DayOfWeek.SATURDAY,
      DayOfWeek.SUNDAY
    };

    String[] dias = new String[7];
    for (int i = 0; i < 7; i++) {
      dias[i] = InputHelper.DayConverter(days[i]);
    }
    c.setModel(new DefaultComboBoxModel(dias));
    c.setSelectedIndex(-1);
  }

  private void setUpHourComboBox(JComboBox c) {
    String[] horas = new String[24];
    for (int i = 0; i < 24; i++) {
      horas[i] = String.format("%02d", i);
    }
    c.setModel(new DefaultComboBoxModel(horas));
    c.setSelectedIndex(-1);
  }

  private void setUpMinuteComboBox(JComboBox c) {
    String[] horas = new String[6];
    for (int i = 0; i < 6; i++) {
      horas[i] = String.format("%02d", i*10);
    }
    c.setModel(new DefaultComboBoxModel(horas));
    c.setSelectedIndex(-1);
  }

  private void setUpHorasDeTrabajoComboBox(JComboBox c) {
    String[] horas = new String[12];
    for (int i = 0; i < 12; i++) {
      horas[i] = String.format("%d", i + 1);
    }
    c.setModel(new DefaultComboBoxModel(horas));
    c.setSelectedIndex(-1);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    diajComboBox = new javax.swing.JComboBox();
    hourjComboBox = new javax.swing.JComboBox();
    minutejComboBox = new javax.swing.JComboBox();
    horasDeTrabajojComboBox = new javax.swing.JComboBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    horariosjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };
    addjButton = new javax.swing.JButton();
    deljButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Ingresar Horarios");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Listo");
    okButton.setMaximumSize(new java.awt.Dimension(112, 27));
    okButton.setMinimumSize(new java.awt.Dimension(112, 27));
    okButton.setPreferredSize(new java.awt.Dimension(112, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    diajComboBox.setToolTipText("Día de trabajo.");
    diajComboBox.setMaximumSize(new java.awt.Dimension(112, 25));
    diajComboBox.setMinimumSize(new java.awt.Dimension(112, 25));
    diajComboBox.setPreferredSize(new java.awt.Dimension(112, 25));

    hourjComboBox.setToolTipText("Hora de comienzo.");
    hourjComboBox.setMaximumSize(new java.awt.Dimension(64, 25));
    hourjComboBox.setMinimumSize(new java.awt.Dimension(64, 25));
    hourjComboBox.setPreferredSize(new java.awt.Dimension(64, 25));

    minutejComboBox.setToolTipText("Minutos de comienzo.");
    minutejComboBox.setMaximumSize(new java.awt.Dimension(64, 25));
    minutejComboBox.setMinimumSize(new java.awt.Dimension(64, 25));
    minutejComboBox.setPreferredSize(new java.awt.Dimension(64, 25));

    horasDeTrabajojComboBox.setToolTipText("Cantidad de horas de trabajo.");
    horasDeTrabajojComboBox.setMaximumSize(new java.awt.Dimension(64, 25));
    horasDeTrabajojComboBox.setMinimumSize(new java.awt.Dimension(64, 25));
    horasDeTrabajojComboBox.setPreferredSize(new java.awt.Dimension(64, 25));

    horariosjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Día", "Desde las", "Hasta las"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    horariosjTable.getTableHeader().setReorderingAllowed(false);
    horariosjTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        horariosjTableMouseClicked(evt);
      }
    });
    jScrollPane1.setViewportView(horariosjTable);

    addjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    addjButton.setMaximumSize(new java.awt.Dimension(44, 25));
    addjButton.setMinimumSize(new java.awt.Dimension(44, 25));
    addjButton.setPreferredSize(new java.awt.Dimension(44, 25));
    addjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addjButtonActionPerformed(evt);
      }
    });

    deljButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/remove.png"))); // NOI18N
    deljButton.setMaximumSize(new java.awt.Dimension(44, 25));
    deljButton.setMinimumSize(new java.awt.Dimension(44, 25));
    deljButton.setPreferredSize(new java.awt.Dimension(44, 25));
    deljButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deljButtonActionPerformed(evt);
      }
    });

    jLabel1.setText("Día");

    jLabel2.setText("hs");

    jLabel3.setText("min");

    jLabel4.setText("Horas");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
              .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(diajComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(104, 104, 104)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addComponent(hourjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addComponent(minutejComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(horasDeTrabajojComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addComponent(jLabel4))))
            .addGap(0, 0, Short.MAX_VALUE)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(jLabel2)
          .addComponent(jLabel3)
          .addComponent(jLabel4))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(diajComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(hourjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(minutejComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(horasDeTrabajojComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(12, 12, 12)
        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(12, 12, 12))
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

  private void addjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButtonActionPerformed
    if (diajComboBox.getSelectedIndex() == -1 || hourjComboBox.getSelectedIndex() == -1 || minutejComboBox.getSelectedIndex() == -1 || horasDeTrabajojComboBox.getSelectedIndex() == -1) {
      JOptionPane.showMessageDialog(this, "No seleccionó todos los ítems. Seleccione todos los ítems del horario, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    int hs = hourjComboBox.getSelectedIndex();
    int min = minutejComboBox.getSelectedIndex() * 10;
    LocalTime desde = LocalTime.of(hs, min);
    LocalTime hasta = desde.plusHours(horasDeTrabajojComboBox.getSelectedIndex() + 1);

    if (desde.isAfter(hasta)) {
      JOptionPane.showMessageDialog(this, "El rango horario excede la duración del día.\nSeleccione un rango horario dentro de las 24 horas de un día, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    HorarioDTO h = new HorarioDTO(
      -1, idMedico,
      DayOfWeek.of(diajComboBox.getSelectedIndex() + 1),
      desde,
      hasta
    );

    horarios.add(h);
    updateHorarios(horarios);

    diajComboBox.setSelectedIndex(-1);
    hourjComboBox.setSelectedIndex(-1);
    minutejComboBox.setSelectedIndex(-1);
    horasDeTrabajojComboBox.setSelectedIndex(-1);
  }//GEN-LAST:event_addjButtonActionPerformed

  private void deljButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButtonActionPerformed
    if (horariosjTable.getSelectedRow() == -1) {
      JOptionPane.showMessageDialog(this, "No seleccionó ningún horario. Seleccione un horario, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    /*
    int ans = JOptionPane.showConfirmDialog(
      this,
      "Eliminar la especialidad " + especialidadSeleccionada.getNombre() + "?",
      "Desea eliminar la especialidad médica seleccionada?",
      JOptionPane.YES_NO_OPTION
    );

    if (ans == JOptionPane.NO_OPTION) {
      return;
    }
    */

    horarios.remove(horariosjTable.getSelectedRow());
    updateHorarios(horarios);
  }//GEN-LAST:event_deljButtonActionPerformed

  private void horariosjTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_horariosjTableMouseClicked
    // TODO add your handling code here:
  }//GEN-LAST:event_horariosjTableMouseClicked
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton addjButton;
  private javax.swing.JButton deljButton;
  private javax.swing.JComboBox diajComboBox;
  private javax.swing.JTable horariosjTable;
  private javax.swing.JComboBox horasDeTrabajojComboBox;
  private javax.swing.JComboBox hourjComboBox;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JComboBox minutejComboBox;
  private javax.swing.JButton okButton;
  // End of variables declaration//GEN-END:variables
  private int returnStatus = RET_CANCEL;
}
